package pers.qianyu.module.image.provider.impl;

import cn.hutool.core.util.IdUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.qianyu.module.core.domain.image.vo.OssTokenVO;
import pers.qianyu.module.image.exception.ImageException;
import pers.qianyu.module.image.properties.AliOssProperties;
import pers.qianyu.module.image.provider.IOssProvider;

import static pers.qianyu.module.image.exception.ImageErrorCodeEnum.GET_OSS_TOKEN_ERROR;

/**
 * @author mizzle rain
 * @date 2021-04-27 15:51
 */
@Service("iOssProvider")
public class IOssProviderImpl implements IOssProvider {
    @Autowired
    private AliOssProperties aliOssProperties;

    @Override
    public OssTokenVO getDirectToken() {
        //构造请求器
        IClientProfile profile = DefaultProfile.getProfile(aliOssProperties.getRegionID(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret());
        DefaultAcsClient client = new DefaultAcsClient(profile);
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleSessionName("lamb");
        request.setRoleArn(aliOssProperties.getRoleArn());
        request.setDurationSeconds(1000L);
        //发送请求
        AssumeRoleResponse acsResponse = null;
        try {
            acsResponse = client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new ImageException(GET_OSS_TOKEN_ERROR);
        }
        AssumeRoleResponse.Credentials credentials = acsResponse.getCredentials();
        //组装一个web需要的对象
        String accessKeyId = credentials.getAccessKeyId();
        String accessKeySecret = credentials.getAccessKeySecret();
        String securityToken = credentials.getSecurityToken();
        OssTokenVO ossTokenVO = new OssTokenVO();
        ossTokenVO.setSecurityToken(securityToken);
        ossTokenVO.setAccessKeyId(accessKeyId);
        ossTokenVO.setAccessKeySecret(accessKeySecret);
        ossTokenVO.setRegion("oss-" + aliOssProperties.getRegionID());
        ossTokenVO.setBucket(aliOssProperties.getBucket());
        ossTokenVO.setUuid(IdUtil.objectId());
        return ossTokenVO;
    }
}
